const http = require('http')
const httpServer = http.createServer(callback) //生成http.server对象，并设置'request'事件的回调函数为callback

function callback(req, res) {
  res.setHeader('Content-Type', 'application/json; charset=utf-8')
  res.statusCode = 200
  res.end(JSON.stringify({code:0, message: 'hello world'}))
}

const port = 3001
httpServer.listen(port) //启动http监听
console.log('server listen on ' + port)



function callback1(req, res) {
  let body = '';
  req.on('data', (chunk) => {  //req没有直接解析请求体
    body += chunk.toString();
  })
  req.on('end', ()=>{
    try{
      const data = JSON.parse(body)
      console.log(data)
    }catch (err){
      console.log(err)
    }
  })
  console.log(req.url)
  console.log(req.method)
  console.log(req.headers)

  res.setHeader('Content-Type', 'application/json; charset=utf-8')
  res.statusCode = 200
  //res.sendDate = false
  res.end(JSON.stringify({code:0, message: 'hello world!'}))
}